import { createI18n } from "vue-i18n";
import en from "./messages/en";
import zh from "./messages/zh";

export const messages = {
  en: {
    ...en,
  },
  zh: {
    ...zh,
  },
};

export const i18n = createI18n({
  legacy: false, // Use Composition API
  locale: localStorage.getItem("lang") || "zh",
  fallbackLocale: "zh",
  messages,
});
export function getLocale() {
  return (
    localStorage.getItem("lang") || navigator.language.substring(0, 2) || "zh"
  );
}
export function setLocale(lang) {
  let _lang = lang || getLocale();
  i18n.global.locale.value = _lang;
  localStorage.setItem("lang", _lang);
}

export function useI18n(app) {
  app.config.globalProperties.$setLocale = setLocale;
  app.config.globalProperties.$getLocale = getLocale;

  app.config.globalProperties.$i18n = i18n;
  app.config.globalProperties.locale = i18n.global.locale;
  // app.config.globalProperties.$t = i18n.global.t;
  app.config.globalProperties.i18n = messages[i18n.global.locale.value];

  app.use(i18n);
  return i18n;
}
